import Router from '@koa/router';
import logger from '../logger.js';
import response from '../response.js';
import { GetOpenID,getPhoneNumber } from '../common/wx.js';
import lsyPay from '../common/lsyPay.js';
import db from '../mysqlHelper.js';
import moment from 'moment';

const router = new Router();
router.prefix('/api');

//车牌识别入场补充证据
// router.post(`/park/camera/carIn`, async (ctx) => {

router.post(`/lsy/applet_pay`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await GetOpenID(body.code);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res.data, '获取OpenID成功');
});
router.post(`/applet/getPhoneNumber`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await getPhoneNumber(body.code);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    if(typeof(res.data)=="string"){
        res.data=JSON.parse(res.data);
    }
    ctx.body = response.success(res.data, '获取手机号成功');
});

//创建预支付订单
router.post(`/applet/advance/createOrder`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.openid == null) {
        ctx.body = response.fail('缺少必填字段 openid');
        return;
    }
    if (body.plate == null) {
        ctx.body = response.fail('缺少必填字段 车牌号');
        return;
    }
    if (body.project_id == null) {
        ctx.body = response.fail('缺少必填字段 项目ID');
        return;
    }
    if (body.amount == null) {
        ctx.body = response.fail('缺少必填字段 充值金额');
        return;
    }

    if (body.order_body == null) {
        body.order_body = `${body.plate} 预支付`;
    }
    let sql=`select project.name, project.isp_id,isp.path from project join isp on project.isp_id=isp.id  where status =1 and project.id=${body.project_id}`;
    let project=await db.query(sql);
    if(project.length==0){
        ctx.body = response.fail('项目不存在或已关闭');
        return;
    }
    let userPayRecord={
        openid:body.openid,
        plate:body.plate,
        isp_id:project[0].isp_id,
        project_id:body.project_id,
        pay_amt:body.amount,
        pay_status:0,
        pay_type:0,
        path:project[0].path,
        create_time:moment().format('YYYY-MM-DD HH:mm:ss'),
        status:0,
        pay_sn:moment().format('YYYYMMDDHHmmssSSS')+Math.floor(Math.random() * 1000000),
    };
    if(body.vin!=null){
        userPayRecord.vin=body.vin;
    }
    if(body.nickname!=null){
        userPayRecord.nickname=body.nickname;
    }
    if(body.phone!=null){
        userPayRecord.phone=body.phone;
    }
    //创建支付订单
    let  res = await lsyPay.applet_pay(userPayRecord.pay_sn, order.price,body.openid, body.order_body);
    if (res.errMsg)
    {
       ctx.body = response.fail('创建支付订单出错:'+ res.errMsg);
       return;
    }
    if (res.return_code != 'SUCCESS') {
        ctx.body = response.fail(res.return_msg);
        return;
    }
     res = await db.create('user_pay_rec', userPayRecord);
    if (res instanceof Error) {
        ctx.body = response.fail('创建订单失败:' + res.message);
        return;
    }
    ctx.body = response.success(res, '创建订单成功');
});
router.all(`/lsy/pay/notify`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if(body.result_code=='PAY_SUCCESS'){
        //支付成功
        let order=await db.findOne('order_info',{pay_sn:body.order_id});
        if(order==null){
            console.error('订单号错误，请使用正确的订单号', JSON.stringify(body));
            ctx.body={return_code:"SUCCESS",return_msg:"订单号错误，请使用正确的订单号"};
            return;
        }
        order.pay_status=1;
        order.pay_time=  moment(body.pay_time,'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss');
        let res = await db.update('order_info',order,{id:order.id});
        if(res instanceof Error){
            console.error('更新订单状态失败',res.message, JSON.stringify(order));
            ctx.body={return_code:"Fail",return_msg:"更新订单状态失败"};
            return;
        }
        console.info('更新订单状态成功', JSON.stringify(order));
        ctx.body={return_code:"SUCCESS",return_msg:"成功"};
    }
    else{
        //支付失败
        console.error('接收到异常的支付回调', JSON.stringify(body));
        ctx.body={return_code:"SUCCESS",return_msg:"成功"};
    }
});

export { router };
